package com.ccsu.mymarket.testUploadFile;

import java.io.IOException;
import java.util.stream.Collectors;

import com.ccsu.mymarket.entity.message.Meta;
import com.ccsu.mymarket.entity.message.Result;
import com.ccsu.mymarket.jwt.PassToken;
import com.ccsu.mymarket.testUploadFile.Storage.StorageFileNotFoundException;
import com.ccsu.mymarket.testUploadFile.Storage.StorageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.method.annotation.MvcUriComponentsBuilder;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;


//上传图片流程：前端发送请求，携带文件，服务器存储后返回虚拟路径，前端使用虚拟路径方能访问
@RestController
@PassToken
@RequestMapping("/img")
public class FileUploadController {
//    构造方法注入，只能选择一个构造方法注入
    private final StorageService storageService;

    @Autowired
    public FileUploadController(StorageService storageService) {
        this.storageService = storageService;
    }

    @GetMapping("/files")
//将图片根目录下所有文件筛选(serveFile方法)后，构造成list存入数据模型(Model)中,初始化作用
    public String listUploadedFiles(Model model) throws IOException {

        model.addAttribute("files", storageService.loadAll().map(
                        path -> MvcUriComponentsBuilder.fromMethodName(FileUploadController.class,
                                "serveFile", path.getFileName().toString()).build().toUri().toString())
                .collect(Collectors.toList()));

        return "uploadForm";
    }

//    ".+"匹配一次及以上点号
//    用户发送文件名，服务器发送指定文件，使用响应头告知服务器进行下载
    @GetMapping("/files/{filename:.+}")
    @ResponseBody
    public ResponseEntity<Resource> serveFile(@PathVariable String filename) {

        Resource file = storageService.loadAsResource(filename);
        return ResponseEntity.ok().header(HttpHeaders.CONTENT_DISPOSITION,
                "attachment; filename=\"" + file.getFilename() + "\"").body(file);
    }

//    用户上传文件，使用MultipartFile类型接收，存储成功后返回文件名
    @PostMapping("/files")
    public Result handleFileUpload(@RequestParam("file") MultipartFile file,
                                   RedirectAttributes redirectAttributes) {

        storageService.store(file);
        String src=file.getOriginalFilename();
        return new Result(new Meta(200,"图片存储成功"),src);
    }

    @ExceptionHandler(StorageFileNotFoundException.class)
    public Result handleStorageFileNotFound(StorageFileNotFoundException exc) {
        return new Result(new Meta(500,"服务器内部错误！"),null);
    }

}
